﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NAutowired.Core.Attributes;
using Starry.Wx.OAuth;
using IH.Service;
using IH.Comm.Dtos.Users;
using IH.Comm.Config;
using Microsoft.Extensions.Options;
using IH.Apis.Filters;

namespace IH.Apis.Controllers
{
    [SkipAuth]
    public class WeixinController : CoreController
    {
        [Autowired]
        private UserService _userService { get; set; }
        [Autowired]
        private OAuthService _authService { get; set; }
        [Autowired]
        protected IOptions<AppSettings> _appSettings { get; set; }

        /// <summary>
        /// 根据微信code获取用户信息
        /// </summary>
        /// <param name="code">换取access_token的票据</param>
        /// <param name="state">暂时没有卵用的</param>
        /// <returns><see cref="UserInfoOutput"/></returns>
        /// <created>tanch,2021/4/4</created>
        /// <changed>tanch,2021/4/4</changed>
        [HttpGet("login")]
        public async Task<UserInfoOutput> WxLogin(string code, string state)
        {
            var accessTokenResult = await _authService.GetAccessTokenAsync(code);
            var wxUserInfo = await _authService.GetUserInfoAsync(accessTokenResult.access_token, accessTokenResult.openid);
            //这里干点注册用户啥的
            var userInfo =await _userService.SaveUserAsync(new UserSaveInput()
            {
                OpenId= wxUserInfo.openid,
                Name= wxUserInfo.nickname,
                HeadPic= wxUserInfo.headimgurl,
                Sex= wxUserInfo.sex
            });
            return userInfo;
        }

        /// <summary>
        /// 获取微信登录地址
        /// </summary>
        /// <param name="url">登录完成后的跳转地址</param>
        /// <returns></returns>
        /// <created>tanch,2021/4/5</created>
        /// <changed>tanch,2021/4/5</changed>
        [HttpGet("LoginUrl")]
        public string GetWxRedirectUrl(string url)
        {
            var wxurl = $"{_appSettings.Value.WeixinConfigs.LoginUrl}?redUrl={System.Net.WebUtility.UrlEncode(url)}";
            return _authService.GetAuthorizeUrl(wxurl);
        }
    }
}
